package com.study.talk.ui.app.home

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.bumptech.glide.Glide
import com.study.talk.R
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.ui.app.friend.AddFriendActivity
import com.study.talk.ui.app.group.AddGroupActivity
import com.study.talk.ui.app.group.create.CreateGroupActivity
import com.study.talk.ui.app.group.GroupNoticeActivity
import com.study.talk.ui.app.other.NewFriendActivity
import com.study.talk.ui.app.self.SelfActivity
import com.study.talk.databinding.ActivityHomeBinding
import com.study.talk.data.net.OkHttp
import com.study.talk.di.AppModule
import com.study.talk.ui.app.change.ChangePwdActivity
import com.study.talk.ui.app.change.ChangeUserInfoActivity
import com.study.talk.utils.extras.start
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class HomeActivity : BaseActivity() {

    companion object {
        private const val TAG = "HomeActivity"
    }

    private val binding: ActivityHomeBinding by lazy { ActivityHomeBinding.inflate(layoutInflater) }

    private val vm: HomeViewModel by viewModels()

    private var loadCache = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        setSupportActionBar(binding.appBarMain.mainToolbar)
        val controller =
            (supportFragmentManager.findFragmentById(R.id.main_nav_host_fragment) as NavHostFragment).navController
        binding.appBarMain.mainNav.setupWithNavController(controller)
        initView()
        binding.appBarMain.mainToolbar.setNavigationOnClickListener {
            if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
                binding.drawerLayout.closeDrawer(GravityCompat.START)
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START)
            }
        }
        binding.leftNavView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {

                R.id.change_user_info -> start(ChangeUserInfoActivity::class.java)

                R.id.change_pwd -> start(ChangePwdActivity::class.java)

                R.id.left_menu_new_friend -> start(NewFriendActivity::class.java)

                R.id.left_menu_group_info -> start(GroupNoticeActivity::class.java)

                R.id.left_menu_exit -> AlertDialog.Builder(this@HomeActivity)
                    .setTitle("退出登录提醒").setMessage("所有的聊天信息都会被清空，您确定要退出吗？")
                    .setNegativeButton("确定") { dialog: DialogInterface, _ ->
                        app.logout()
                        dialog.dismiss()
                        finish()
                    }.setPositiveButton(
                        "取消",
                        (DialogInterface.OnClickListener { dialog: DialogInterface, i: Int -> dialog.dismiss() })
                    ).show()
            }
            true
        }
        first()
    }

    private fun first() {
        val preferences = getSharedPreferences("account", Context.MODE_PRIVATE)
        if (preferences.getBoolean("first", true)) {
            preferences.edit().putBoolean("first", false).apply()
            vm.loadAllMsg()
        }
    }

    override fun onStart() {
        super.onStart()
        //加载缓存在服务器的未读消息
        if (loadCache) {
            loadCache = false
            vm.loadCacheMsg()
        }
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    @SuppressLint("NonConstantResourceId")
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.main_menu_add_friend -> start(AddFriendActivity::class.java)
            R.id.main_menu_add_group -> start(AddGroupActivity::class.java)
            R.id.main_menu_create_group -> start(CreateGroupActivity::class.java)
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initView() {
        val headerView = binding.leftNavView.getHeaderView(0)
        headerView.setOnClickListener {
            start(SelfActivity::class.java)
        }
        val accountHeadImg = headerView.findViewById<ImageView>(R.id.account_head_img)
        val accountUsername = headerView.findViewById<TextView>(R.id.account_username)
        val accountIntroduce = headerView.findViewById<TextView>(R.id.account_introduce)
        Glide.with(this@HomeActivity).load(AppModule.getWebUrl() + app.userInfo.avatar).into(accountHeadImg)
        accountUsername.text = app.userInfo.nickName
        accountIntroduce.text = app.userInfo.introduce
    }
}